package fi.vamk.android;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

public class Contact extends ListActivity {
	TextView selection;
	private String[] stringNameArray; 
	private String[] stringPhoneArray;
	private String[] stringEmailArray;
	private EditText mailTitle;
	private EditText mailBody;
    @Override
    public void onCreate(Bundle icicle) {
    	super.onCreate(icicle);
        setContentView(R.layout.contacts);
       
        		
        String jsonString = menuList.contact; 
        JSONArray json = null;
        try {
            json = new JSONArray(jsonString);
        } catch (JSONException je) {
            Log.e("TAG", "Json Exception" + je.getMessage() );
            return;
        }
     JSONObject jsonObject = null;
     ArrayList<String> arrayNameList = new ArrayList<String>();
     ArrayList<String> arrayPhoneList = new ArrayList<String>();
     ArrayList<String> arrayEmailList = new ArrayList<String>();
     for (int i = 0; i < json.length(); i++) {
            try {
                jsonObject = json.getJSONObject(i);
                    if(jsonObject.has("name"))
                     {
                       String stuName = jsonObject.getString("name");
                       String stuPhone = jsonObject.getString("phonenumber");
                       String stuEmail = jsonObject.getString("email");
                       arrayNameList.add(stuName);
                       arrayPhoneList.add(stuPhone);
                       arrayEmailList.add(stuEmail);
                     }     

                 
            } catch (JSONException jee) {
                Log.e("TAG", "" + jee.getMessage());
            }

        }
        stringNameArray = arrayNameList.toArray(new String[arrayNameList.size()]);
        stringPhoneArray = arrayPhoneList.toArray(new String[arrayPhoneList.size()]);
        stringEmailArray = arrayEmailList.toArray(new String[arrayEmailList.size()]);
	     try {
	    	 
	    	 setListAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, stringNameArray));
	        		 selection=(TextView)findViewById(R.id.selection);
		} catch (Exception e) {
			// TODO: handle exception
			alertOkOnly("Exception!"  , e.toString());
		}
    
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.layout.menu_button, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
        case R.id.exit:
        	finish();
            return true;
        case R.id.list:
        	startActivity(new Intent(Contact.this, menuList.class));
         	finish();
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }
     public void onListItemClick( ListView parent, View v, int position, long id) {
     		try {
     			String mess = stringNameArray[position];
     			contactMenu(mess, position);
     			//selection.setText(name[position]);
			} catch (Exception e) {
				// TODO: handle exception
				alertOkOnly("Exception!", e.toString());
			}
    }
    public void contactMenu(String title, int position)
    {
    	final int positionInt = position;
    	final CharSequence[] items = {"Call", "SMS", "Email"};
    	AlertDialog.Builder builder=
        	new AlertDialog.Builder(Contact.this);
        	builder
        	.setTitle(title)
        	//.setMessage(message)
        	.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
	            public void onClick(DialogInterface dialog, int item)
	            {
	            	if (item == 0 )
	            	{
	            		String toDial="tel:"+stringPhoneArray[positionInt].toString();
	            		startActivity(new Intent(Intent.ACTION_DIAL,
	            		Uri.parse(toDial)));
	            	}
	            	else if (item == 1 )
	            	{
	            		startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("sms:"
                                + stringPhoneArray[positionInt].toString())));
	            	}
	            	else{
	            		mailDialog("send Email to " + stringNameArray[positionInt].toString(), stringEmailArray[positionInt].toString());
	            		
	            	}
	            	
	            }
	        })
              
             .setNegativeButton("Ok", null)      
        	.show();
    }
    public void alertOkOnly(String title, String message)
    {
    	AlertDialog.Builder builder=
        	new AlertDialog.Builder(Contact.this);
        	builder
        	.setTitle(title)
        	.setMessage(message)
        	.setPositiveButton("OK", null)
        	.show();
    } 
    public void mailDialog(String title, String email)
    {
    	final String emailAddress = email;
    	LayoutInflater inflater = Contact.this.getLayoutInflater();
    	final View inflator = inflater.inflate(R.layout.mail, null);
    	final AlertDialog.Builder builder=
        	new AlertDialog.Builder(Contact.this);
        	builder
        	.setTitle(title)
        	.setView(inflater.inflate(R.layout.mail, null))
        	.setPositiveButton("Send", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface d, int choice) {
                    // on OK button action
                    	try {
                    		mailTitle=(EditText)inflator.findViewById(R.id.title);
                        	mailBody=(EditText)inflator.findViewById(R.id.body);
                        	String title = mailTitle.getEditableText().toString();
                        	String body = mailBody.getEditableText().toString();
                        	Intent i = new Intent(Intent.ACTION_SEND);
                        	i.setType("text/plain");
                        	i.putExtra(Intent.EXTRA_EMAIL  , new String[]{emailAddress});
                        	i.putExtra(Intent.EXTRA_SUBJECT, title);
                        	i.putExtra(Intent.EXTRA_TEXT   , body);
                        	try {
                        	    startActivity(Intent.createChooser(i, "Send mail..."));
                        	} catch (android.content.ActivityNotFoundException ex) {
                        	    //Toast.makeText(contact.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
                        	    alertOkOnly("Email Client Error", "There are no email clients installed.");
                        	}
						} catch (Exception e) {
							// TODO: handle exception
							alertOkOnly("Exception", e.toString());
						}
                    }
                    })
             .setNegativeButton("Cancel", null)      
        	.show();
    } 
    }
